package com.jinzecloud.reportapproval.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.config.ConfigureBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;

@Slf4j
@Component
public class WordUtil {

    public static String profileActive;

    @Value("${spring.profiles.active}")
    public void setProfileActive(String profileActive) {
        WordUtil.profileActive = profileActive;
    }

    public static XWPFTemplate getWord(String templatePath, JSONObject data, ConfigureBuilder builder) {
        XWPFTemplate template = null;
        if (StrUtil.equals(profileActive, "dev")) {
            String path = Objects.requireNonNull(WordUtil.class.getClassLoader().getResource(templatePath)).getPath();
            template = XWPFTemplate.compile(path, builder.build()).render(data);
        } else {
            InputStream inputStream = WordUtil.class.getClassLoader().getResourceAsStream(templatePath);
            if (inputStream == null) return null;
            template = XWPFTemplate.compile(inputStream, builder.build()).render(data);
        }
        return template;
    }

    public static File getWordFile(String templatePath, JSONObject data, ConfigureBuilder builder) {
        File tempFile = FileUtil.createTempFile(".docx", true);
        try (XWPFTemplate template = getWord(templatePath, data, builder)){
            if (template == null) return null;
            template.writeToFile(tempFile.getPath());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return tempFile;
    }

    public static File getWordFile(String templatePath, JSONObject data) {
        return getWordFile(templatePath, data, Configure.builder());
    }

}
